package com.batdream.message.service.impl;

import com.batdream.message.mapper.MyFriendsMapper;
import com.batdream.message.mapper.UsersMapper;
import com.batdream.message.mapper.UsersMapperCustom;
import com.batdream.message.pojo.FriendsRequest;
import com.batdream.message.pojo.MyFriends;
import com.batdream.message.pojo.Users;
import com.batdream.message.pojo.vo.FriendRequestVo;
import com.batdream.message.pojo.vo.UserVo;
import com.batdream.message.service.FileService;
import com.batdream.message.service.MyFriendsService;
import com.batdream.message.service.UserService;
import com.batdream.message.service.friendsRequestService;
import com.batdream.message.utils.JSONResult;
import com.batdream.message.utils.MD5Utils;
import com.batdream.message.utils.QRCodeUtils;
import com.batdream.message.utils.idworker.Sid;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * @author Wang Chen Peng
 * @date 2018/12/25
 * describe:
 */
@Service
@Log4j2
public class UserServiceImpl implements UserService {

    private final UsersMapper usersMapper;
    private final QRCodeUtils qrCodeUtils;
    private final Sid sid;
    private final FileService fileService;
    private final MyFriendsMapper myFriendsMapper;
    private final MyFriendsService myFriendsService;
    private final friendsRequestService requestService;
    private final UsersMapperCustom usersMapperCustom;
    private final friendsRequestService friendsRequestService;

    @Autowired
    public UserServiceImpl(UsersMapper usersMapper, Sid sid, QRCodeUtils qrCodeUtils, FileService fileService, MyFriendsMapper myFriendsMapper, MyFriendsService myFriendsService, friendsRequestService requestService, UsersMapperCustom usersMapperCustom, friendsRequestService friendsRequestService) {

        this.usersMapper = usersMapper;
        this.sid = sid;
        this.qrCodeUtils = qrCodeUtils;
        this.fileService = fileService;
        this.myFriendsMapper = myFriendsMapper;
        this.myFriendsService = myFriendsService;
        this.requestService = requestService;
        this.usersMapperCustom = usersMapperCustom;
        this.friendsRequestService = friendsRequestService;
    }

    @Override
    public boolean queryUsername(String username) {

        Users users = new Users();
        users.setUsername(username);
        Users result = usersMapper.selectOne(users);

        return result != null;
    }

    @Override
    public JSONResult login(Users users) throws Exception {

        Example userExample = new Example(Users.class);
        Example.Criteria criteria = userExample.createCriteria();
        criteria.andEqualTo("username", users.getUsername());
        criteria.andEqualTo("password", MD5Utils.getMD5Str(users.getPassword()));

        Users result = usersMapper.selectOneByExample(userExample);
        if (result != null) {
            return JSONResult.ok(result);
        } else {
            return JSONResult.errorMsg("用户名或密码不正确");
        }
    }

    @Override
    public JSONResult register(Users users) throws Exception {
        //先获取id
        String id = sid.nextShort();
        //获取生成的二维码保存的路径
        String path = fileService.getPathByUserId(id);
        //生成二维码到本地磁盘缓存
        qrCodeUtils.createQRCode(path, "qr_code:"+id);
        //上传二维码到fastDFS并获得大图以及缩略图
        String result = fileService.saveImgByPath(path);
        Users user = new Users();
        user.setUsername(users.getUsername())
                .setFaceImage("")
                .setFaceImageBig("")
                .setPassword(MD5Utils.getMD5Str(users.getPassword()))
                .setId(id)
                .setNickname(users.getUsername())
                .setCid(user.getCid());

        if (!StringUtils.isEmpty(result)){
            user.setQrcode(result);
        }else{
            log.error("二维码生成失败 请求用户信息为 : {}",user);
        }
        //保存
        usersMapper.insert(user);
        //创建vo对象 并进行对象间拷贝
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);

        return JSONResult.ok(userVo);
    }


    @Override
    public int updateUserImg(String userId, String saveBigImgUrl, String saveMicroImgUrl) {
        Users user = new Users();
        user.setId(userId).setFaceImageBig(saveBigImgUrl).setFaceImage(saveMicroImgUrl);
        return usersMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public Users queryUserById(String userId) {
        return usersMapper.selectByPrimaryKey(userId);
    }

    @Override
    public JSONResult updateNickName(Users users) {
        if (StringUtils.isEmpty(users.getNickname())){
            return JSONResult.errorMsg("昵称不能为空");
        }
        if (StringUtils.isEmpty(users.getId())){
            return JSONResult.errorMsg("用户id不能为空");
        }
        return JSONResult.ok(updateUserInfo(users));
    }

    @Override
    public JSONResult searchUser(String myUserId, String friendUserName) {
        //用户是否存在
        Users users = queryUserByUserName(friendUserName);
        if (Objects.isNull(users)){
            return JSONResult.errorMsg("搜索的用户不存在");
        }

        //是否搜索的是自己
        if (myUserId.equals(users.getId())){
            return JSONResult.errorMsg("不能搜索自己");
        }

        //是否已是好友
        MyFriends friends = new MyFriends();
        friends.setMyUserId(myUserId);
        friends.setMyFriendUserId(users.getId());
        MyFriends myFriends = myFriendsService.searchMyfriendByUsersId(friends);
        if (Objects.nonNull(myFriends)){
            return JSONResult.errorMsg("你和他已经是朋友");
        }

        return JSONResult.ok(users);
    }

    @Override
    public JSONResult addFirend(String myUserId, String friendId) {

        Users my = usersMapper.selectByPrimaryKey(myUserId);
        if (Objects.isNull(my)){
            return JSONResult.errorMsg("发起请求的用户不存在");
        }
        Users friend = usersMapper.selectByPrimaryKey(friendId);
        if (Objects.isNull(friend)){
            return JSONResult.errorMsg("被添加的用户不存在");
        }
        //是否已是好友
        MyFriends friends = new MyFriends();
        friends.setMyUserId(myUserId);
        friends.setMyFriendUserId(friendId);
        MyFriends myFriends = myFriendsService.searchMyfriendByUsersId(friends);
        if (Objects.nonNull(myFriends)){
            return JSONResult.errorMsg("你和他已经是朋友");
        }

        FriendsRequest friendsRequest = new FriendsRequest();
        friendsRequest.setSendUserId(my.getId());
        friendsRequest.setAcceptUserId(friend.getId());
        friendsRequest = friendsRequestService.searchrequestbyTwinsId(friendsRequest);
        if (Objects.nonNull(friendsRequest)){
            return JSONResult.errorMsg("已经发送过请求了,请等待对方处理请求后再发送");
        }

        FriendsRequest request = new FriendsRequest();
        request.setId(Sid.next());
        request.setSendUserId(myUserId);
        request.setAcceptUserId(friendId);
        request.setRequestDateTime(new Date());
        Integer saveNum = requestService.saveRequest(request);
        if (Objects.isNull(saveNum)){
            return JSONResult.errorMsg("发送请求失败,请重试");
        }
        return JSONResult.ok();
    }

    @Override
    public List<FriendRequestVo> queryFriendRequestList(String acceptUserId) {

        Users my = usersMapper.selectByPrimaryKey(acceptUserId);
        if (Objects.isNull(my)){
            throw new RuntimeException("用户不存在");
        }

        return usersMapperCustom.queryFriendRequestList(acceptUserId);
    }

    @Override
    public JSONResult scanQrCodeSearchUserById(String myUserId, String friendId) {
        //用户是否存在
        Users my = usersMapper.selectByPrimaryKey(myUserId);
        if (Objects.isNull(my)){
            return JSONResult.errorMsg("用户id不正确");
        }
        friendId = friendId.replace("qr_code:", "");
        Users friend = usersMapper.selectByPrimaryKey(friendId);
        if (Objects.isNull(friend)){
            return JSONResult.errorMsg("查询的用户不存在");
        }

        //是否搜索的是自己
        if (myUserId.equals(friend.getId())){
            return JSONResult.errorMsg("不能扫描自己的二维码");
        }

        return JSONResult.ok(friend);
    }

    /**
     * 根据用户id 查询数据库
     * @param user 包含用户id
     * @return result
     */
    private Users updateUserInfo(Users user) {
        usersMapper.updateByPrimaryKeySelective(user);
        return queryUserById(user.getId());
    }

    /**
     * 根据用户名查询数据库
     * @param userName 用户名
     * @return result
     */
    private Users queryUserByUserName(String userName){
        Example userExample = new Example(Users.class);
        Example.Criteria criteria = userExample.createCriteria();
        criteria.andEqualTo("username", userName);

        return usersMapper.selectOneByExample(userExample);
    }
}
